package wnhz.com.business.rebateshop.activity.home;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.groupshop.bean.ShareInfo;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.StringDialogCallback;
import wnhz.com.business.rebateshop.bean.ShareBean;
import wnhz.com.business.shareshop.bean.MyCollectionShareBean;
import wnhz.com.business.shareshop.ui.MyCollectActivityS;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 分享商品给好友
 */
public class ShareFriandActivity extends MyBaseActivity implements ActionBarClickListener {


    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.ll_pengyouquan)
    LinearLayout llPengyouquan;
    @BindView(R.id.ll_weixinhaoyou)
    LinearLayout llWeixinhaoyou;
    @BindView(R.id.ll_qq)
    LinearLayout llQq;
    @BindView(R.id.ll_qzon)
    LinearLayout llQzon;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_skuinfo)
    TextView tvSkuinfo;
    @BindView(R.id.tv_price)
    TextView tvPrice;

    private int resId;
    private ShareAction shareAction;
    //分享
    private ShareInfo shareInfo = new ShareInfo();
    private UMShareListener umShareListener;

    private PopupWindow sharepop;
    private TextView tv_ok;
    private RelativeLayout rl_body;
    private int type;
    private String url,logo,name,skuInfo,store_id,goodsId;

    public static Intent createIntent(Context context,String logo,String skuInfo,String name,String price) {
        Intent intent = new Intent(context, ShareFriandActivity.class);
        intent.putExtra("logo",logo);
        intent.putExtra("name",name);
        intent.putExtra("skuInfo",skuInfo);
        intent.putExtra("price",price);
        return intent;
    }
    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, ShareFriandActivity.class);
        return intent;
    }
    private void paseIntent() {
          logo = getIntent().getStringExtra("logo");
          name = getIntent().getStringExtra("name");
          skuInfo = getIntent().getStringExtra("skuInfo");
        store_id = getIntent().getStringExtra("store_id");
        goodsId = getIntent().getStringExtra("goodsId");
        String price = getIntent().getStringExtra("price");
        if (!TextUtils.isEmpty(logo)){
            Glide.with(ShareFriandActivity.this).load(logo).into(ivIcon);
        }
        if (!TextUtils.isEmpty(name)){
           tvName.setText(name);
        }
        if (!TextUtils.isEmpty(skuInfo)){
            tvSkuinfo.setVisibility(View.VISIBLE);
           tvSkuinfo.setText(skuInfo);
        }else {
            tvSkuinfo.setVisibility(View.INVISIBLE);
        }
        if (!TextUtils.isEmpty(price)){
           tvPrice.setText("¥"+price);
        }
    }
    @Override
    protected void handleMsg(Message msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_friand);
        ButterKnife.bind(this);
        paseIntent();
        actionbar.setData("分享商品给好友", R.drawable.ic_lefft_white, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        getUrl();
    }



    private void initview() {

        shareInfo.title = name;
        if(TextUtils.isEmpty(skuInfo)){
            shareInfo.text = "永惠多多";
        }else{
            shareInfo.text = skuInfo;
        }
        shareInfo.targetUrl = url;
        shareAction = new ShareAction(this);
        shareAction.withTitle(TextUtils.isEmpty(shareInfo.title) ? getString(R.string.app_name) : shareInfo.title);
        if (!TextUtils.isEmpty(shareInfo.text)) {//shareAction.withText一定不能為空，不然跳轉回失敗
            shareAction.withText(shareInfo.text);
        } else {
            throw new NullPointerException("shareAction 中的 text 不可为空");
        }
        if (!TextUtils.isEmpty(shareInfo.targetUrl)) {
            shareAction.withTargetUrl(shareInfo.targetUrl);
        } else {
            throw new NullPointerException("shareAction 中的 targetUrl 不可为空");
        }
if(TextUtils.isEmpty(logo)){
    UMImage image = new UMImage(this, R.mipmap.iconn);
    shareAction.withMedia(image);
}else{
    UMImage image = new UMImage(this, logo);
    shareAction.withMedia(image);
}

        umShareListener = new UMShareListener() {
            @Override
            public void onResult(SHARE_MEDIA share_media) {
                addShareNum();
                Toast.makeText(ShareFriandActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                Toast.makeText(ShareFriandActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                Toast.makeText(ShareFriandActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
            }
        };
    }


    //分享成功弹窗
    private void seepop(){
        View contentView = LayoutInflater.from(this).inflate(R.layout.item_layout_shareok, null);
        sharepop = new PopupWindow(contentView);
        sharepop.setOutsideTouchable(true);
        sharepop.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        sharepop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);

        if (Build.VERSION.SDK_INT < 24) {
            sharepop.showAsDropDown(actionbar);
        } else {
            // 获取控件的位置，安卓系统>7.0
            int[] location = new int[2];
            actionbar.getLocationOnScreen(location);
            sharepop.showAtLocation(actionbar, Gravity.NO_GRAVITY, 0, location[1] + actionbar.getHeight());
        }


        tv_ok = (TextView)contentView.findViewById(R.id.tv_ok);
        rl_body = (RelativeLayout) contentView.findViewById(R.id.rl_body);
        //确认
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sharepop.dismiss();
            }
        });

        //整体
        rl_body.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sharepop.dismiss();
            }
        });


    }


    private void getUrl() {
        Map<String,Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        XUtil.Post(Url.GOODS_SHARE_URL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.getString("re");
                    if ("1".equals(re)) {
                        Gson gson = new Gson();
                        ShareBean item = gson.fromJson(result, ShareBean.class);
                        url = item.getInfo().getUrl();
                        initview();
//                        if( type == 1){
//                            shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener).share();
//                        }else if( type == 2){
//                            shareAction.setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener).share();
//                        }else if( type == 3){
//                            shareAction.setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener).share();
//                        }else if( type == 4){
//                            shareAction.setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener).share();
//                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });}

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
    }

    @Override
    public void onEditTextClick() {
    }

    @OnClick({R.id.ll_pengyouquan, R.id.ll_weixinhaoyou, R.id.ll_qq, R.id.ll_qzon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_pengyouquan:
                type = 1;
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener).share();
                break;
            case R.id.ll_weixinhaoyou:
                type = 2;
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener).share();
                break;
            case R.id.ll_qq:
                type = 3;
                shareAction.setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener).share();
                break;
            case R.id.ll_qzon:
                type = 4;
                shareAction.setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener).share();
                break;
        }
    }
    private void addShareNum() {//增加分享次数
        Map<String, String> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        /**
         @param Str   token
         @param Int   goodsId     商品id
         @param Int   store_id    店铺id
         @param Int   goods_type  1.拼团  2.返利  3.免费
         */
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("goodsId", goodsId);
        map.put("store_id", store_id);
        map.put("goods_type","2");//1.拼团  2.返利  3.免费
        OkGo.<String>post(Url.GOODS_GOODSSHARE)
                .tag(this)
                .params(map,false)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("==商品详情-分享增加次数==",response.body().toString());
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String re = jsonObject.optString("re");
                        if ("1".equals(re)){
                            seepop();
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });


    }
}
